package com.xl.rentkeeper.receiver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.SystemClock;

import com.xl.rentkeeper.App;
import com.xl.rentkeeper.business.KeepAliveLogic;
import com.xl.rentkeeper.log.QLog;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by Administrator on 2015/7/15.
 */
public class KeepAliveReceiver extends BroadcastReceiver {
    public static final String action_boot="android.intent.action.BOOT_COMPLETED";
    public static final String action_alarm_keepalive="com.xl.fuse.KEEP_ALIVE";
    public static  int hbindex = 0;
    private long time;
    @Override
    public void onReceive(Context context, Intent intent) {
        if(intent.getAction().equals(Intent.ACTION_SCREEN_ON)){
//            request("SCREEN_ON");
            KeepAliveLogic.getInstance().doHB();
        }else if(intent.getAction().equals(action_alarm_keepalive)){
            App.addAlarm(SystemClock.elapsedRealtime()+App.hbTime);
//            request("ALARM");8
            KeepAliveLogic.getInstance().doHB();
        }
    }
    public void request(final String type){
        time = System.currentTimeMillis();
        hbindex++;
        new Thread(new Runnable(){
            @Override
            public void run() {
                try{
                    URL url = new URL("http://www.baidu.com");
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.setConnectTimeout(6 * 1000);
                    if(conn!=null){
                        int code = conn.getResponseCode();
                        time = System.currentTimeMillis()-time;
                        QLog.d("HB", "data:"+getDate()+" index:" + hbindex + " ResponseCode:" + code +" type:"+type+" time:"+time+"MS");
                    }
                }catch (MalformedURLException e){
                    time = System.currentTimeMillis()-time;
                    QLog.d("HB", "data:"+getDate()+" index:"+hbindex+" exception:"+e.getMessage() +" type:"+type+" time:"+time+"MS");
                }catch (IOException e2){
                    time = System.currentTimeMillis()-time;
                    QLog.d("HB", "data:"+getDate()+" index:"+hbindex+" exception:"+e2.getMessage() +" type:"+type+" time:"+time+"MS");
                }catch (Exception e3){
                    time = System.currentTimeMillis()-time;
                    QLog.d("HB", "data:"+getDate()+" index:"+hbindex+" exception:"+e3.getMessage() +" type:"+type+" time:"+time+"MS");
                }

            }
        }).start();
    }
    public String getDate(){
        String time = null;
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        time = df.format(new Date());
        return time;
    }
}
